package com.rran.study.chat.gateway.util;

import io.fusionauth.jwt.Verifier;
import io.fusionauth.jwt.domain.JWT;
import io.fusionauth.jwt.json.Mapper;
import io.fusionauth.jwt.rsa.RSAVerifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.Map;


@Component
@Slf4j
public class JWTUtil {


//  @Value("${rsa.publicKey}")
  private String pubicKey= "";


  /**
   * rsa token 解密
   */
  public JWT decryptToken(String token) throws Exception {
//    log.debug("pubicKey= "+pubicKey);
    Verifier verifier = RSAVerifier.newVerifier(pubicKey);
    JWT decode = JWT.getDecoder().decode(token, verifier);
    return decode;
  }

  /**
   * 校验 token 是否过期
   */
  public Boolean verifyExp(String token) throws Exception {
    return checkEXP(decryptToken(token));
  }


  /**
   * 根据当前时间和 jwt 的 exp 时间相比,没过期返回 true
   */
  public Boolean checkEXP(JWT jwt) {//判断是否过期
    Map<String, Object> allClaims = jwt.getAllClaims();
    ZonedDateTime exp = (ZonedDateTime) allClaims.get("exp");
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")));
    return exp.isAfter(now);
  }

  /**
   * 根据当前时间和 jwt 的 exp 时间相比, 当前时间小说明为过期
   */

  public  JWT parseJWT(String token) {
    String[] split = token.split("\\.");
    byte[] decode = Base64.getUrlDecoder().decode(split[1]);
    JWT jwt = Mapper.deserialize(decode, JWT.class);

    return jwt;
  }


  public static void main(String[] args) {
String toke=
        "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjcxNjU1MDgsImlhdCI6MTU2NzE1ODMwOCwiaXNzIjoiZ3d0IFNlcnZlciIsImJlYW5JZCI6IjE3Nzk2MjAyNDg4NTM0NTQ4NTAiLCJyb2xlQ29kZSI6InVzZXIifQ.APFzl-RTLb8uO2sIqac-9EeciJq0YVCbKcO6gK43GLE-1wtmHFzeaWvMM0DuYvSdh7mhFpw_ELfEg-jPCGvU5NRn_TPkrhZdRcYMPZHqllO9K5A68f_13q38Xu7GOYFkbGqH2XHqc0ZgxGIM0FRU4aAm0TvJNgKOlb4eI_Lp2RdSVAN7EKTmft-n836YN9wWTfr52npg80_H5i8zudOw1nzU_85sggpZB8Ncvhr2r9yioZwC7Otlw2CnkQaSpSdddMOKnxxhltCwEbOMjlkPtK1zxQ6VaMsq6spQobE55L5IUGcdnQqtoiVAZ4RjiM6ZgO47CXc8jeGlv3RqLZUAdDPxf8I-wns"
        ;
JWTUtil jwtUtil = new JWTUtil();
    JWT jwt = null;
    try {
      jwt = jwtUtil.decryptToken(toke);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(jwt);
//    System.out.println(jwt.isExpired());
  }

}
